package request;

import java.io.OutputStream;

import response.ResponseBuddyInvite;
import core.GameUser;
import core.Constants;
import core.GameCharacter;
import core.Message;
import java.util.Vector;

/**
 * Class that handles "add buddy" request.
 * When user sends this request, asking to add a buddy to his list,
 * the player whom he wants to add must acknowledge this
 * and must agree to be on user's buddy-list.
 *
 * @author Zoran
 *
 */
public class RequestBuddyInvite extends GameRequest{
	// User who requested to add a buddy.
	private GameUser sender;
	private GameUser receiver = null;
        private String receiverName; // User's character name.
	// Invitation-Message
	private Message message;
	// Reference to a user who will be asked to be the buddy

        public RequestBuddyInvite() {
            code = Constants.CMSG_BUDDY_INVITE;
        }
	public void parse() {
            try {
                // Protocol: (String) CharacterName, (String) message
                sender = client.getUser();
                receiverName = client.readString(dataIn);

                message = new Message();
                message.setSender(sender.getCharacter().getName());
                message.setText(client.readString(dataIn));

                gameServer.log("BuddyInvite from " + message.getSender() + " to " + receiverName + ": " + message.getText());
                GameCharacter character = gameServer.getGameDB().getCharacter(receiverName);
                if(character != null) {
                   receiver = new GameUser(character.getUserID());
                   gameServer.getGameDB().getUser(receiver.getID(), receiver);
                }

            } catch(Exception e){
                gameServer.log("RequestBuddyInvite error:" + receiverName,"e");
            }
	}

        @Override
	public void respond(OutputStream output) {

            // Create sendBuddyInvite response
            ResponseBuddyInvite response = new ResponseBuddyInvite();

            // Set response status.
            if(receiver != null) {
                if (!receiver.getOnline()) {
                    response.setStatus((short)0); // User not online.
                }
                else {
                    gameServer.addBuddyInvite(receiver.getUsername(), message);
                    response.setStatus((short)1); // Success.
                }
            }
            else {
                response.setStatus((short)-1); // User not found.
            }

            response.set(gameServer);
            response.setOut(output);
            response.run();

	}
}